package com.ktwlrj.securitycenter.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktwlrj.core.base.DetailEntity;
import com.ktwlrj.core.constant.ResultCode;
import com.ktwlrj.core.exception.ActionException;
import com.ktwlrj.core.util.ContextHolderUtils;
import com.ktwlrj.core.util.convert.ConvertUtil;
import com.ktwlrj.securitycenter.controller.args.AddSafeApproveArgs;
import com.ktwlrj.securitycenter.controller.args.SafeApproveArgs;
import com.ktwlrj.securitycenter.controller.args.SafeCredentialArgs;
import com.ktwlrj.securitycenter.controller.args.SafeCredentialInfoArgs;
import com.ktwlrj.securitycenter.controller.args.SafeSpecialApplyArgs;
import com.ktwlrj.securitycenter.controller.args.SafeSpecialApprovePageArgs;
import com.ktwlrj.securitycenter.controller.args.SafeSpecialFormArgs;
import com.ktwlrj.securitycenter.controller.args.SafeSpecialPageArgs;
import com.ktwlrj.securitycenter.dto.SafeApproveDto;
import com.ktwlrj.securitycenter.dto.SafeCredentialDto;
import com.ktwlrj.securitycenter.dto.SafeSpecialApprovePageDto;
import com.ktwlrj.securitycenter.dto.SafeSpecialDto;
import com.ktwlrj.securitycenter.dto.SafeSpecialFormDto;
import com.ktwlrj.securitycenter.dto.SafeSpecialPageDto;
import com.ktwlrj.securitycenter.dto.SafeSpecialRuleDto;
import com.ktwlrj.securitycenter.dto.SafeSpecialTargetDto;
import com.ktwlrj.securitycenter.em.LockStatusEnum;
import com.ktwlrj.securitycenter.entity.SafeSpecialEntity;
import com.ktwlrj.securitycenter.entity.SafeSpecialRuleEntity;
import com.ktwlrj.securitycenter.entity.SafeSpecialTargetEntity;
import com.ktwlrj.securitycenter.mapper.SafeSpecialMapper;
import com.ktwlrj.securitycenter.mapper.SafeSpecialRuleMapper;
import com.ktwlrj.securitycenter.mapper.SafeSpecialTargetMapper;
import com.ktwlrj.securitycenter.service.SafeApproveService;
import com.ktwlrj.securitycenter.service.SafeCredentialService;
import com.ktwlrj.securitycenter.service.SafeSpecialRuleService;
import com.ktwlrj.securitycenter.service.SafeSpecialService;
import com.ktwlrj.securitycenter.service.SafeSpecialTargetService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * (SafeSpecial)业务层实现
 *
 * @author code generation
 * @date 2020-02-24 18:08:13
 * @since JDK1.8
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SafeSpecialServiceImpl extends ServiceImpl<SafeSpecialMapper, SafeSpecialEntity>
		implements SafeSpecialService {
	private final SafeSpecialMapper mapper;
	private final SafeSpecialTargetService specialTargetService;
	private final SafeSpecialRuleService specialRuleService;
	private final SafeSpecialTargetMapper specialTargetMapper;
	private final SafeSpecialRuleMapper specialRuleMapper;
	private final SafeCredentialService credentialService;
	private final SafeApproveService approveService;
	private final ContextHolderUtils contextHolderUtils;

	@Override
	public void save(SafeSpecialFormArgs args) throws RuntimeException {
		if (StringUtils.isBlank(args.getSafeSpecial().getRuleCode())) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "规则编号不能为空");
		}
		if (args.getSafeSpecialTargetList().size() <= 0) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "限制对象不能为空");
		}
		if (args.getSafeSpecialRuleList().size() <= 0) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "限制人员不能为空");
		}
		DetailEntity detailEntity = contextHolderUtils.getDetailEntity();
		SafeSpecialEntity entity = ConvertUtil.map(args.getSafeSpecial(), SafeSpecialEntity.class);
		entity.setSpecialId(null);
		entity.setApproveStatus(0);
		entity.setVersion(null);
		entity.setTargetCount(args.getSafeSpecialTargetList().size());
		entity.setPersonCount(args.getSafeSpecialRuleList().size());
		entity.setOrgId(detailEntity.getCurrentOrgId());
		entity.setOrgName(detailEntity.getCurrentOrgName());
		super.save(entity);
		// 对象信息
		List<SafeSpecialTargetEntity> specialTargeList = ConvertUtil.listAtoListB(args.getSafeSpecialTargetList(),
				SafeSpecialTargetEntity.class);
		for (SafeSpecialTargetEntity item : specialTargeList) {
			item.setSpecialId(entity.getSpecialId());
			item.setSpecialTargetId(null);
			if (item.getScope() == 1) {
				item.setDataCode(item.getProjectCode());
			}
			if (item.getScope() == 2) {
				item.setDataCode(item.getSaleCertificate());
			}
			if (item.getScope() == 3) {
				item.setDataCode(item.getBuildingNumber());
			}
			if (item.getScope() == 4) {
				item.setDataCode(item.getRoomNumber());
			}
		}
		specialTargetService.saveBatch(specialTargeList);
		// 规则信息
		List<SafeSpecialRuleEntity> specialRuleList = ConvertUtil.listAtoListB(args.getSafeSpecialRuleList(),
				SafeSpecialRuleEntity.class);
		for (SafeSpecialRuleEntity item : specialRuleList) {
			item.setSpecialId(entity.getSpecialId());
			item.setSpecialRuleId(null);
		}
		specialRuleService.saveBatch(specialRuleList);
		// 添加要件信息
		for (SafeCredentialArgs item : args.getCredentialList()) {
			item.setBusiId(entity.getSpecialId());
			item.setCredentialId(null);
			List<SafeCredentialInfoArgs> credentialInfoList = item.getCredentialInfoList();
			for (SafeCredentialInfoArgs itemInfo : credentialInfoList) {
				itemInfo.setCredentialInfoId(null);
			}
		}
		credentialService.batchSave(args.getCredentialList());
	}

	@Override
	public void updateById(SafeSpecialFormArgs args) throws RuntimeException {
		if (StringUtils.isBlank(args.getSafeSpecial().getSpecialId())) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "特殊房屋半交易id不能为空");
		}
		if (StringUtils.isBlank(args.getSafeSpecial().getRuleCode())) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "规则编号不能为空");
		}
		if (args.getSafeSpecialTargetList().size() <= 0) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "限制对象不能为空");
		}
		if (args.getSafeSpecialRuleList().size() <= 0) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "限制人员不能为空");
		}
		SafeSpecialEntity entity = super.getById(args.getSafeSpecial().getSpecialId());
		if (entity == null) {
			throw new ActionException(ResultCode.DATABASE_NODATA);
		}
		if (entity.getLockStatus() != null && entity.getLockStatus() != 10) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "当前记录处于锁定状态");
		}
		DetailEntity detailEntity = contextHolderUtils.getDetailEntity();
		entity = ConvertUtil.map(args.getSafeSpecial(), SafeSpecialEntity.class);
		entity.setApproveStatus(0);
		entity.setTargetCount(args.getSafeSpecialTargetList().size());
		entity.setPersonCount(args.getSafeSpecialRuleList().size());
		entity.setOrgId(detailEntity.getCurrentOrgId());
		entity.setOrgName(detailEntity.getCurrentOrgName());
		super.updateById(entity);
		// 对象信息
		QueryWrapper<SafeSpecialTargetEntity> targetQueryWrapper = new QueryWrapper<>();
		targetQueryWrapper.lambda().eq(SafeSpecialTargetEntity::getSpecialId, args.getSafeSpecial().getSpecialId());
		specialTargetMapper.delete(targetQueryWrapper);
		List<SafeSpecialTargetEntity> specialTargeList = ConvertUtil.listAtoListB(args.getSafeSpecialTargetList(),
				SafeSpecialTargetEntity.class);
		for (SafeSpecialTargetEntity item : specialTargeList) {
			item.setSpecialTargetId(null);
			item.setSpecialId(entity.getSpecialId());
			if (item.getScope() == 1) {
				item.setDataCode(item.getProjectCode());
			}
			if (item.getScope() == 2) {
				item.setDataCode(item.getSaleCertificate());
			}
			if (item.getScope() == 3) {
				item.setDataCode(item.getBuildingNumber());
			}
			if (item.getScope() == 4) {
				item.setDataCode(item.getRoomNumber());
			}
		}
		specialTargetService.saveBatch(specialTargeList);
		// 规则信息
		QueryWrapper<SafeSpecialRuleEntity> ruleQueryWrapper = new QueryWrapper<>();
		ruleQueryWrapper.lambda().eq(SafeSpecialRuleEntity::getSpecialId, args.getSafeSpecial().getSpecialId());
		specialRuleMapper.delete(ruleQueryWrapper);
		List<SafeSpecialRuleEntity> specialRuleList = ConvertUtil.listAtoListB(args.getSafeSpecialRuleList(),
				SafeSpecialRuleEntity.class);
		for (SafeSpecialRuleEntity item : specialRuleList) {
			item.setSpecialRuleId(null);
			item.setSpecialId(entity.getSpecialId());
		}
		specialRuleService.saveBatch(specialRuleList);
		// 添加要件信息
		for (SafeCredentialArgs item : args.getCredentialList()) {
			item.setBusiId(entity.getSpecialId());
			item.setCredentialId(null);
		}
		credentialService.batchSave(args.getCredentialList());
	}

	@Override
	public IPage<SafeSpecialPageDto> page(SafeSpecialPageArgs args) throws RuntimeException {
		args.setOrgId(contextHolderUtils.getCurrentOrgId());
		return mapper.page(args.getQueryPage(), args);
	}

	@Override
	public IPage<SafeSpecialPageDto> historyPage(SafeSpecialPageArgs args) throws RuntimeException {
		args.setOrgId(contextHolderUtils.getCurrentOrgId());
		return mapper.historyPage(args.getQueryPage(), args);
	}

	@Override
	public SafeSpecialFormDto getById(String id) throws RuntimeException {
		SafeSpecialFormDto safeSpecialFormDto = new SafeSpecialFormDto();
		SafeSpecialEntity byId = super.getById(id);
		if (byId == null) {
			throw new ActionException(ResultCode.DATABASE_NODATA);
		}
		SafeSpecialDto safeSpecial = ConvertUtil.map(byId, SafeSpecialDto.class);
		safeSpecialFormDto.setSafeSpecial(safeSpecial);
		// 特殊房屋交易对象
		QueryWrapper<SafeSpecialTargetEntity> targetQueryWrapper = new QueryWrapper<>();
		targetQueryWrapper.lambda().eq(SafeSpecialTargetEntity::getSpecialId, id);
		List<SafeSpecialTargetEntity> specialTargetEntityList = specialTargetMapper.selectList(targetQueryWrapper);
		List<SafeSpecialTargetDto> safeSpecialTargetList = ConvertUtil.listAtoListB(specialTargetEntityList,
				SafeSpecialTargetDto.class);
		safeSpecialFormDto.setSafeSpecialTargetList(safeSpecialTargetList);
		// 特殊房屋交易规则
		QueryWrapper<SafeSpecialRuleEntity> ruleQueryWrapper = new QueryWrapper<>();
		ruleQueryWrapper.lambda().eq(SafeSpecialRuleEntity::getSpecialId, id);
		List<SafeSpecialRuleEntity> specialRuleEntityList = specialRuleMapper.selectList(ruleQueryWrapper);
		List<SafeSpecialRuleDto> safeSpecialRuleList = ConvertUtil.listAtoListB(specialRuleEntityList,
				SafeSpecialRuleDto.class);
		safeSpecialFormDto.setSafeSpecialRuleList(safeSpecialRuleList);
		// 要件信息
		List<SafeCredentialDto> safeCredentialList = credentialService.selectListByModel(id);
		safeSpecialFormDto.setSafeCredentialList(safeCredentialList);
		// 审批意见
		List<SafeApproveDto> safeApproveList = approveService.selectByBusinessId(id);
		safeSpecialFormDto.setSafeApproveList(safeApproveList);
		return safeSpecialFormDto;
	}

	@Override
	public void submit(SafeSpecialApplyArgs args) throws RuntimeException {
		SafeSpecialEntity entity = super.getById(args.getSpecialId());
		if (entity == null) {
			throw new ActionException(ResultCode.DATABASE_NODATA);
		}
		// 新增
		if (entity.getSpecialType() == 1) {
			entity.setApproveStatus(10);
		}
		// 变更
		if (entity.getSpecialType() == 2) {
			QueryWrapper<SafeSpecialEntity> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(SafeSpecialEntity::getSpecialCode, entity.getSpecialCode());
			queryWrapper.lambda().eq(SafeSpecialEntity::getApproveStatus, 20);
			SafeSpecialEntity historySafeSpecialEntity = mapper.selectOne(queryWrapper);
			// 新数据已提交
			entity.setApproveStatus(10);
			// 老数据变更中
			historySafeSpecialEntity.setLockStatus(LockStatusEnum.LOGGING_OUT.getValue());
			mapper.updateById(historySafeSpecialEntity);
		}
		mapper.updateById(entity);
		// 审批意见
		AddSafeApproveArgs addSafeApproveArgs = new AddSafeApproveArgs();
		addSafeApproveArgs.setBusinessId(entity.getSpecialId());
		addSafeApproveArgs.setApproveType(entity.getSpecialType());
		addSafeApproveArgs.setHandlePersonId(args.getHandlePersonId());
		addSafeApproveArgs.setHandlePersonName(args.getHandlePersonName());
		approveService.save(addSafeApproveArgs);
	}

	@Override
	public void changeInsert(SafeSpecialFormArgs args) throws RuntimeException {
		// 查询数据是否存在
		SafeSpecialEntity entity = super.getById(args.getSafeSpecial().getSpecialId());
		if (entity == null) {
			throw new ActionException(ResultCode.DATA_INPUT_EMPTY.getValue(), "未查询到当前数据");
		}
		if (entity.getApproveStatus() != 20) {
			throw new ActionException(ResultCode.AUTH_ACCESS_DENIED.getValue(), "审批状态未通过，不能变更");
		}
		if (entity.getLockStatus() != null && entity.getLockStatus() != LockStatusEnum.NORMAL.getValue()) {
			throw new ActionException(ResultCode.AUTH_ACCESS_DENIED.getValue(), "当前数据处理锁定状态");
		}
		entity.setLockStatus(LockStatusEnum.LOGGING_OUT.getValue());
		boolean result = super.updateById(entity);
		if (!result) {
			throw new ActionException(ResultCode.DATABASE_UPDATE_ERROR);
		}
		// 保存
		args.getSafeSpecial().setSpecialCode(args.getSafeSpecial().getSpecialCode());
		this.save(args);
	}

	@Override
	public void deleteById(String id) throws RuntimeException {
		SafeSpecialEntity byId = super.getById(id);
		if (byId == null) {
			throw new ActionException(ResultCode.DATABASE_NODATA);
		}
		if (byId.getApproveStatus() != 0 && byId.getApproveStatus() != 30) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "当前记录不能被删除");
		}
		// 原数据恢复锁定状态
		QueryWrapper<SafeSpecialEntity> specialQueryWrapper = new QueryWrapper<>();
		specialQueryWrapper.lambda().ne(SafeSpecialEntity::getSpecialId, id);
		specialQueryWrapper.lambda().eq(SafeSpecialEntity::getSpecialCode, byId.getSpecialCode());
		specialQueryWrapper.lambda().eq(SafeSpecialEntity::getApproveStatus, 20);
		SafeSpecialEntity safeSpecialEntity = mapper.selectOne(specialQueryWrapper);
		if (safeSpecialEntity != null) {
			safeSpecialEntity.setLockStatus(10);
			mapper.updateById(safeSpecialEntity);
		}
		// 删除数据
		mapper.deleteById(id);
		// 特殊房屋交易对象
		QueryWrapper<SafeSpecialTargetEntity> targetQueryWrapper = new QueryWrapper<>();
		targetQueryWrapper.lambda().eq(SafeSpecialTargetEntity::getSpecialId, id);
		specialTargetMapper.delete(targetQueryWrapper);
		// 特殊房屋交易规则
		QueryWrapper<SafeSpecialRuleEntity> ruleQueryWrapper = new QueryWrapper<>();
		ruleQueryWrapper.lambda().eq(SafeSpecialRuleEntity::getSpecialId, id);
		specialRuleMapper.delete(ruleQueryWrapper);
		// 要件信息
		credentialService.deleteByBusiId(id);
		// 审批意见
		approveService.deleteByBusinessId(id);
	}

	@Override
	public void deleteApply(SafeSpecialApplyArgs args) {
		SafeSpecialEntity entity = super.getById(args.getSpecialId());
		if (entity == null) {
			throw new ActionException(ResultCode.DATABASE_NODATA);
		}
		entity.setLockStatus(LockStatusEnum.CANCELLING.getValue());
		mapper.updateById(entity);
		// 要件信息
		appendCredential(args);
		// 审批意见
		AddSafeApproveArgs addSafeApproveArgs = new AddSafeApproveArgs();
		addSafeApproveArgs.setBusinessId(entity.getSpecialId());
		addSafeApproveArgs.setApproveType(3);
		addSafeApproveArgs.setHandlePersonId(args.getHandlePersonId());
		addSafeApproveArgs.setHandlePersonName(args.getHandlePersonName());
		approveService.save(addSafeApproveArgs);
	}

	/**
	 * 追加要件信息
	 *
	 * @param args
	 *            请求参数
	 */
	private void appendCredential(SafeSpecialApplyArgs args) {
		if (args.getCredentialInfoList() != null && args.getCredentialInfoList().size() > 0) {
			List<SafeCredentialDto> credentialDtoList = credentialService.selectListByModel(args.getSpecialId());
			List<SafeCredentialArgs> credentialArgsList = new ArrayList<>();
			if (credentialDtoList != null && credentialDtoList.size() > 0) {
				credentialArgsList = ConvertUtil.listAtoListB(credentialDtoList, SafeCredentialArgs.class);
			} else {
				SafeCredentialArgs safeCredentialArgs = new SafeCredentialArgs();
				safeCredentialArgs.setBusiId(args.getSpecialId());
				safeCredentialArgs.setCredentialType("复印件");
				safeCredentialArgs.setCredentialName("凭证");
				safeCredentialArgs.setCredentialCount(1);
				safeCredentialArgs.setCredentialPage(1);
				safeCredentialArgs.setFileType(0);
				safeCredentialArgs.setSortId(0);
				safeCredentialArgs.setInterOperateType(1);
				safeCredentialArgs.setNetOperateType(1);
				credentialArgsList.add(safeCredentialArgs);
			}
			for (SafeCredentialArgs item : credentialArgsList) {
				if (item.getCredentialName().equals("凭证")) {
					item.getCredentialInfoList().addAll(args.getCredentialInfoList());
					break;
				}
			}
			credentialService.batchSave(credentialArgsList);
		}
	}

	@Override
	public IPage<SafeSpecialApprovePageDto> approvePage(SafeSpecialApprovePageArgs args) throws RuntimeException {
		DetailEntity detailEntity = contextHolderUtils.getDetailEntity();
		args.setOrgId(detailEntity.getCurrentOrgId());
		args.setMemberId(detailEntity.getMemberId());
		return mapper.approvePage(args.getQueryPage(), args);
	}

	@Override
	public void approveHandle(SafeApproveArgs args) {
		// 查询数据是否存在
		SafeApproveDto approveDto = approveService.getById(args.getApproveId());
		SafeSpecialEntity safeSpecialEntity = super.getById(args.getBusinessId());
		// 已经通过的数据置为历史
		QueryWrapper<SafeSpecialEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(SafeSpecialEntity::getSpecialCode, safeSpecialEntity.getSpecialCode());
		queryWrapper.lambda().eq(SafeSpecialEntity::getApproveStatus, 20);
		SafeSpecialEntity historysafeSpecialEntity = mapper.selectOne(queryWrapper);
		// 已通过
		if (args.getHandleResult() == 1) {
			// 新增
			if (approveDto.getApproveType() == 1) {
				safeSpecialEntity.setApproveStatus(20);
				safeSpecialEntity.setVersion(1);
				safeSpecialEntity.setApproveTime(new Date());
				safeSpecialEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
			}
			// 变更
			if (approveDto.getApproveType() == 2) {
				if (historysafeSpecialEntity == null) {
					throw new ActionException(ResultCode.VERIFICATION_FAILED, "未查询到变更前数据");
				}
				// 新数据审批状态已通过
				safeSpecialEntity.setApproveStatus(20);
				safeSpecialEntity.setVersion(historysafeSpecialEntity.getVersion() + 1);
				safeSpecialEntity.setApproveTime(new Date());
				safeSpecialEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
				// 老数据审批状态历史
				historysafeSpecialEntity.setApproveStatus(40);
				historysafeSpecialEntity.setHistoryType(20);
				mapper.updateById(historysafeSpecialEntity);
			}
			// 删除
			if (approveDto.getApproveType() == 3) {
				safeSpecialEntity.setApproveStatus(40);
				safeSpecialEntity.setApproveTime(new Date());
				safeSpecialEntity.setHistoryType(30);
				safeSpecialEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
			}
		}
		// 驳回
		if (args.getHandleResult() == 2) {
			// 新增
			if (approveDto.getApproveType() == 1) {
				safeSpecialEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
				safeSpecialEntity.setApproveStatus(30);
			}
			// 变更
			if (approveDto.getApproveType() == 2) {
				if (historysafeSpecialEntity == null) {
					throw new ActionException(ResultCode.VERIFICATION_FAILED, "未查询到变更前数据");
				}
				// 新数据审批状态未通过
				safeSpecialEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
				safeSpecialEntity.setApproveStatus(30);
				// 老数据审批状态已通过
				historysafeSpecialEntity.setApproveStatus(20);
				historysafeSpecialEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
				mapper.updateById(historysafeSpecialEntity);
			}
			// 删除
			if (approveDto.getApproveType() == 3) {
				safeSpecialEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
			}
		}
		// 更新当前数据
		mapper.updateById(safeSpecialEntity);
		// 审批意见
		approveService.approveSave(args);
	}
}